import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Validators, FormControl, FormGroup, FormBuilder} from '@angular/forms';
import { routerTransition } from '../../router.animations';
import { SettingsService } from '../../core/settings/settings.service';
import {AuthService} from '../../core/service/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
  animations: [routerTransition()]
})
export class LoginComponent implements OnInit {
  loginForm: FormGroup;
  constructor(private router: Router, private formBuilder: FormBuilder,
              private auth: AuthService, private settings: SettingsService) {
    this.createForm();
  }

  // 创建用户登录表单
  createForm () {
    const username = new FormControl('sysadmin',
      Validators.compose([Validators.required, Validators.minLength(6),
        Validators.maxLength(15)]));
    const password = new FormControl('sysadmin',
      Validators.compose([Validators.required,
        Validators.minLength(6), Validators.maxLength(15)]));
    this.loginForm = this.formBuilder.group({
      username: username,
      password: password
    });
  }
  ngOnInit() {
    // 如果用户是登录状态，直接跳到主页
    if (localStorage.getItem('access_token')) {
      this.router.navigate(['/']);
    }
  }

  login () {
    if (this.loginForm.valid) {
      this.auth.login({'username': this.loginForm.get('username').value, 'password': this.loginForm.get('password').value})
        .then(() => {
          this.router.navigate(['/']);
      });
    }
  }

}
